//
//  ZBBaseViewController.m
//  AFNetworking
//
//  Created by xzb on 2018/6/3.
//

#import "ZBBaseViewController.h"
#import "Aspects.h"
#import "ZBMacros.h"
#import "ZBHUD.h"
#import "UIColor+ZBColor.h"
#import "ZBNavigationDelegate.h"
#import "ZBColorHeader.h"

#ifdef DEBUG
#import <ZBUitilty/ZBFpsTool.h>
#endif


static const CGFloat kZBNavigationBarHeight = 44;

@interface ZBBaseViewController () <ZBNavigationDelegate>

@end

@implementation ZBBaseViewController

+ (void)hookSelectorStr:(NSString *)selector  usingBlock:(id)block option:(AspectOptions)option
{
    NSError *error = nil;
    [self aspect_hookSelector:NSSelectorFromString(selector)  withOptions:AspectPositionBefore usingBlock:block error:&error];
    if (error) {
        Log(@"Load error: %@", error);
    }
}

+ (void)load
{
    [ZBBaseViewController hookSelectorStr:@"viewDidLoad" usingBlock:^(id<AspectInfo> aspectInfo) {
        ZBBaseViewController *vc = [aspectInfo instance];
        [vc ZB_addSubView];
        [vc ZB_addLayout];
        [vc ZB_loadData];
    } option: AspectPositionBefore];
    [ZBBaseViewController hookSelectorStr:@"viewDidLoad" usingBlock:^(id<AspectInfo> aspectInfo) {
        ZBBaseViewController *vc = [aspectInfo instance];
        [vc ZB_sendQuery];
        [vc zb_bringNavigationBarToFront];
    } option: AspectPositionAfter];
    
    [ZBBaseViewController hookSelectorStr:@"viewWillAppear:" usingBlock:^(id<AspectInfo> aspectInfo) {
        ZBBaseViewController *vc = [aspectInfo instance];
        if ([vc firstResponderTextField] && ([vc firstResponderTextField].text.length > 0)) {
            if ([[vc firstResponderTextField] canBecomeFirstResponder]) {
                [[vc firstResponderTextField] becomeFirstResponder];
            }
        } else {
            if ([vc firstResponderTextField] && [[vc firstResponderTextField] canResignFirstResponder]) {
                [[vc firstResponderTextField] resignFirstResponder];
            }
        }
    } option: AspectPositionAfter];
    [ZBBaseViewController hookSelectorStr:@"viewWillDisappear:" usingBlock:^(id<AspectInfo> aspectInfo) {
        ZBBaseViewController *vc = [aspectInfo instance];
        [vc.view endEditing:YES];
        [ZBHUD hidden];
    }option: AspectPositionAfter];
}

// ⚠️
// 假如不实现此方法，系统在加载 View 的时候（并应当去自动查找同名的 xib），还会去试图加载去掉 Controller 之后的名称的 xib，
// 这样就造成了一些问题
// 如：
//   - https://bugly.qq.com/v2/crash-reporting/crashes/48b2930153/1715426?pid=2
//   - https://bugly.qq.com/v2/crash-reporting/crashes/48b2930153/1715575?pid=2
// 等等
- (void)loadView
{
    [super loadView];
}
#pragma mark - life cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = kBackgroundColor_Controller;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
  
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.statusView];
    
    if (self.navigationController) {
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        if (_navigationBar && _navigationBar.backBtn) {
            BOOL showBackBtn =  self.navigationController.viewControllers.count > 1;
            self.navigationBar.backBtn.hidden = !showBackBtn;
        }
    }
    
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    self.statusView.frame = UIApplication.sharedApplication.statusBarFrame;
    
    self.navigationBar.frame = CGRectMake(0, CGRectGetMaxY(self.statusView.frame), CGRectGetWidth(self.view.frame), kZBNavigationBarHeight);
}


- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation
{
    return UIStatusBarAnimationNone;
}

- (BOOL)prefersStatusBarHidden
{
    return NO;
}

- (BOOL)shouldAutorotate
{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

#pragma mark - api

- (UITextField *)firstResponderTextField
{
    return nil;
}

#pragma mark - Delegete

#pragma mark - Event Response

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
#pragma mark - private methods

- (void)ZB_addSubView
{
}

- (void)ZB_addLayout
{
}

- (void)ZB_loadData
{
    self.view.backgroundColor = [UIColor colorWithHexString:@"f1f2f6" alpha:1];
}

- (void)ZB_sendQuery
{
}

- (void)zb_bringNavigationBarToFront
{
    if (_navigationBar) {
        [self.view bringSubviewToFront:self.navigationBar];
    }
}
#pragma mark - ZBNavigationDelegate

- (BOOL)zb_shouldPanback
{
    return YES;
}

#pragma mark - get/set

- (void)setTitle:(NSString *)title
{
    [super setTitle:title];
    if (_navigationBar) {
        self.navigationBar.titleLabel.text = title;
    }
}
- (ZBNavigationBar *)navigationBar
{
    if (!_navigationBar) {
        _navigationBar = [[ZBNavigationBar alloc] init];
#ifdef DEBUG
        __block UILabel *fpsLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 50, 15)];
        fpsLabel.font = kFontSize(12);
        fpsLabel.textColor = [UIColor redColor];
        [_navigationBar addSubview:fpsLabel];
        [[ZBFpsTool instance] openWithHandler:^(NSInteger fpsValue) {
            fpsLabel.text = [NSString stringWithFormat:@"fps-%d",(int)round(fpsValue)];
        }];
#endif
    }
    return _navigationBar;
}

- (UIView *)statusView
{
    if (!_statusView) {
        _statusView = [[UIView alloc] init];
        _statusView.backgroundColor = [UIColor whiteColor];
    }
    return _statusView;
}

- (CGFloat)navigationBarBottom
{
    return CGRectGetHeight(UIApplication.sharedApplication.statusBarFrame) + kZBNavigationBarHeight;
}

@end
